library(leaflet)
library(sf)
library(dplyr)
# Build a summary sf for each district (join district polygons with your Q3 table)
district_summary <- nyc_districts |>
left_join(
q3_dead_fraction |> select(CounDist, n_trees, n_dead, frac_dead),
by = "CounDist"
) |>
mutate(
borough = case_when(
CounDist >= 1 & CounDist <= 10 ~ "Manhattan",
CounDist >= 11 & CounDist <= 18 ~ "Bronx",
CounDist >= 19 & CounDist <= 32 ~ "Queens",
CounDist >= 33 & CounDist <= 48 ~ "Brooklyn",
CounDist >= 49 & CounDist <= 51 ~ "Staten Island",
TRUE ~ NA_character_
)
)
# Color palette for dead-tree fraction
pal_dead <- colorNumeric(
palette = "YlOrRd",
domain = district_summary$frac_dead,
na.color = "#CCCCCC"
)
leaflet() |>
addProviderTiles("CartoDB.Positron") |>
# all districts, filled by dead-tree fraction
addPolygons(
data = district_summary,
fillColor = ~pal_dead(frac_dead),
fillOpacity = 0.7,
weight = 1,
color = "#555555",
popup = ~sprintf(
"District %d (%s)<br/>Trees: %s<br/>Dead trees: %s (%.1f%%)",
CounDist,
borough,
format(n_trees, big.mark = ","),
format(n_dead, big.mark = ","),
100 * frac_dead
),
label = ~paste0("District ", CounDist, " (", borough, ")")
) |>
# outline District 32 so your proposal district pops out
addPolygons(
data = district_summary |> filter(CounDist == 32),
fill = FALSE,
weight = 3,
color = "black"
) |>
addLegend(
position = "bottomright",
pal = pal_dead,
values = district_summary$frac_dead,
title = "Fraction of dead trees",
labFormat = leaflet::labelFormat(transform = function(x) 100 * x, suffix = "%")
) |>
setView(lng = -73.94, lat = 40.72, zoom = 10)